<!-- 添加推广链接 -->
<!-- 添加推广链接 -->
<template>
  <el-dialog
      v-model="dialogVisible"
      width="500px"
      title="百度联调"
      draggable
      appendToBody
      destroyOnClose
      lockScroll
      :closeOnClickModal="false"
  >
    <el-form ref="elFormRef" :model="formData" :rules="rules">


      <el-form-item label="推广URL" labelWidth="8em" prop="promotionUrl">
        <el-input v-model="formData.promotionUrl" :maxlength="800" clearable placeholder="请填写推广URL"></el-input>
      </el-form-item>

      <el-form-item key="el-form-item-4" labelWidth="0em">
        <div style="width: 100%; padding-top: 20px">
          <el-button style="width: 100%" type="success" :disabled="loading" :loading="loading" @click="submit">保存
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import type {FormInstance, FormRules} from 'element-plus';
import {vAutoAnimate} from '@formkit/auto-animate/vue';
import IconPointer from '~icons/ep/pointer';
import {
  type BaseBackTemplate,
  type Drama,
  type Episode,
  type IaaBaseBackTemplate,
  type MpInfo,
  type ReferralLink,
  type ReferralRecord,
  type ReferralTemplate,
  type TemplateProductMarketingInfo,
  addReferralRecordAxios,
  editReferralRecordAxios,
  getAllBackTemplateListAxios,
  getDramaListAxios,
  getEpisodeListAxios,
  getIAAAllBackTemplateListAxios,
  baiduLiantiao,
  getMpInfoAxios,
  getTemplateInfoByReferralLinkId,
} from '@/api/marketing-management';
import {filterRepeat} from '@/utils/data';
import PageSelectTemplate from '@/components/page/page-select-template/page-select-template.vue';

type $EditShowData = {
  /** 操作 */
  action: 'clone' | 'edit';
  referralRecord: ReferralRecord;
  /** 审核后的回调 */
  editCallBack?: () => void;
};

type $AddShowData = {
  /** 操作 */
  action: 'add';
  /** 审核后的回调 */
  addCallBack?: () => void;
};

type $DetailsShowData = {
  /** 操作 */
  action: 'details';
  referralRecord: ReferralRecord;
};

type SelectType = { label: string; value: string };

type $ShowData = $AddShowData | $DetailsShowData | $EditShowData;
type FormData = Omit<ReferralLink, 'dramaId' | 'episodeId' | 'productBackTemplateId'> & {
  /** 短剧信息 */
  drama: Drama | undefined;
  /** 剧集信息 */
  episode: Episode | undefined;
  /** 渠道列表 */
  channel: MpInfo['investmentChannel'] | '';
  /** 平台列表 */
  platform: MpInfo['platformType'] | '';
  /** 小程序 */
  appid: MpInfo['appId'] | '';
  /** 投广渠道-平台关联id */
  investmentId: MpInfo['investmentId'] | '';
  dramaFirstTemplate: TemplateProductMarketingInfo;
};

const pageLoad = shallowReactive<$PageLoad>({loadState: true, description: ''});

let addCallBack: $AddShowData['addCallBack'] = undefined;
let editCallBack: $EditShowData['editCallBack'] = undefined;

const dialogVisible = ref(false);
const elFormRef: Ref<FormInstance | null> = ref(null);
const pageSelectTemplateRef: Ref<InstanceType<typeof PageSelectTemplate> | null> = ref(null);
const action = ref<'add' | 'clone' | 'details' | 'edit'>();
const loading = ref(false);
const mpInfoLIst = shallowRef<MpInfo[]>([]);
const episodeList = ref<Episode[]>([]);

const disabled = computed(() => action.value === 'details');

const formData = reactive<FormData>({
  referralLinkName: '',
  drama: undefined,
  episode: undefined,
  pushPlatform: 1,
  referralLinkId: null,
  remark: '',
  channel: 'juliang',
  platform: 'mp-weixin',
  iaaFlag: 0,
  appid: '',
  appCode: '',
  investmentId: undefined,
  price: null,
  rechargeEpisodeNum: null,
  productTemplateId: undefined,
  advertUnlock: 0,
  dramaFirstTemplate: {
    templateName: '',
    templateType: 4,
    selectIndex: 0,
    advertUnlock: 0,
    productList: [],
  },
});
/** IAP回传模版信息 */
const iapBackTemplate = ref<BaseBackTemplate | undefined>(undefined);
/** IAA回传模版信息 */
const iaaBackTemplate = ref<IaaBaseBackTemplate | undefined>(undefined);

/** 渠道列表 */
const channelList = computed(() => {
  const list = filterRepeat(mpInfoLIst.value, 'investmentChannel').map((item) => ({
    label: item.investmentChannelName,
    value: item.investmentChannel,
  }));

  console.log(list, '==================', mpInfoLIst.value);
  return list;
});

/** 平台列表 */
const platformList = computed<SelectType[]>(() => {
  if (formData.channel) {
    const list: SelectType[] = [];
    mpInfoLIst.value.forEach((item) => {
      if (formData.channel === item.investmentChannel) {
        list.push({label: item.platformName, value: item.platformType});
      }
    });
    return filterRepeat(list, 'value');
  } else {
    return [];
  }
});

/** 小程序列表 */
const mpList = computed(() => {
  if (formData.channel && formData.platform) {
    const list: { label: string; value: string; investmentId: number; iaaFlag: 0 | 1 }[] = [];
    mpInfoLIst.value.forEach((item) => {
      if (formData.channel === item.investmentChannel && formData.platform === item.platformType && item.iaaFlag === formData.iaaFlag) {
        list.push({label: item.appName, value: item.appId, investmentId: item.investmentId!, iaaFlag: item.iaaFlag});
      }
    });
    return filterRepeat(list, 'value');
  } else {
    return [];
  }
});

const rules = computed(() => {
  const _rules: FormRules<FormData> = {

    promotionUrl: [{required: true, message: '请输入推广Url', trigger: ['blur', 'change']}],
  };
  return _rules;
});

/**
 * 提交
 */
async function submit() {
  try {
    await elFormRef.value?.validate();
    try {
      loading.value = true;
      selectChannelAndPlatform();
      const data: ReferralLink = {
        referralLinkId: formData.referralLinkId,
        promotionUrl: formData.promotionUrl
      };


      let callback = await baiduLiantiao(data);
      loading.value = false;
      ElToast.success('操作成功');
      hide();
    } catch (error) {
      console.log('aaa====', error);
      loading.value = false;
      ElToast.error(error.msg || '提交失败，-BD001');
    }
  } catch (error) {
    ElToast.error('提交失败，请完善表单，-BD002');
  }
}

const initFormData = () => {
  iapBackTemplate.value = undefined;
  iaaBackTemplate.value = undefined;
  formData.referralLinkName = '';
  formData.drama = undefined;
  formData.channel = 'juliang';
  formData.platform = 'mp-weixin';
  formData.iaaFlag = 0;
  formData.appCode = '';
  formData.investmentId = undefined;
  formData.episode = undefined;
  formData.pushPlatform = 1;
  formData.referralLinkId = null;
  formData.price = null;
  formData.rechargeEpisodeNum = null;
  formData.remark = '';
  formData.productTemplateId = undefined;
  formData.advertUnlock = 0;
  formData.dramaFirstTemplate = {
    templateName: '',
    templateType: 4,
    selectIndex: 0,
    advertUnlock: 0,
    productList: [],
  };
};

/**
 * 显示
 */
function show(data: $ShowData) {
  action.value = data.action;
  initFormData();

  if (data.action === 'edit' || data.action === 'clone' || data.action === 'details') {
    formData.promotionUrl = ''
    formData.referralLinkId = data.referralRecord.referralLinkId || '';
  }

  addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
  editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;

  dialogVisible.value = true;
}

/**
 * 隐藏
 */
function hide() {
  dialogVisible.value = false;
}

/** 请求 */
async function getBaseDataAxios() {
  try {
    pageLoad.loadState = true;

    const res = await Promise.all(
        formData.referralLinkId ? [getMpInfoAxios(), getTemplateInfoByReferralLinkId(formData.referralLinkId)] : [getMpInfoAxios()]
    );

    console.log(res, 'rrrrrrrrrr');

    mpInfoLIst.value = res[0].data || [];
    if (res[1]) {
      iapBackTemplate.value = res[1].data.productTemplateId
          ? {
            productBackTemplateId: res[1].data.productBackTemplateId,
            backTemplateName: res[1].data.backTemplateName || ''
          }
          : undefined;
      iaaBackTemplate.value = res[1].data.iaaBackTemplateId
          ? {iaaBackTemplateId: res[1].data.iaaBackTemplateId, iaaRuleName: res[1].data.iaaRuleName || ''}
          : undefined;
      formData.dramaFirstTemplate = {
        ...res[1].data,
        productList: res[1].data.productList || [],
        templateName: res[1].data.templateName || '',
        templateType: res[1].data.templateType || 4,
        selectIndex: res[1].data.selectIndex || 0,
        advertUnlock: res[1].data.advertUnlock || 0,

      };
    }
    formData.baiduToken = res[1].data.baiduToken || ''
    const mpInfo = mpInfoLIst.value.find((item) => item.investmentId === formData.investmentId);
    formData.iaaFlag = mpInfo?.iaaFlag || 0;

    pageLoad.loadState = false;
    if (action.value === 'edit' || action.value === 'clone' || action.value === 'details') {
      selectChannelAndPlatform();
    }
  } catch (error) {
    pageLoad.loadState = 'err';
    pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
  }
}

/** 编辑回显渠道和平台 */
function selectChannelAndPlatform() {
  if (formData.investmentId) {
    const mpInfo = mpInfoLIst.value.find((item) => item.investmentId === formData.investmentId);
    if (mpInfo) {
      formData.channel = mpInfo.investmentChannel;
      formData.iaaFlag = mpInfo.iaaFlag;
      formData.platform = mpInfo.platformType;
      formData.appCode = mpInfo.appCode;
    }
  }
}

/** 短剧变更填充默认剧集 */
async function dramaChangeHandler(val: Drama) {
  try {
    formData.episode = undefined;
    const {data} = await getEpisodeListAxios({dramaId: val.dramaId});
    episodeList.value = data ?? [];
    if (data.length) {
      formData.episode = data[0];
    }
  } catch (error) {
  }
}

/** 渠道变更重置平台 */
function channelChangeHandler() {
  formData.platform = '';
  formData.investmentId = undefined;
}

/** 平台变更重置小程序 */
function platformListChangeHandler() {
  formData.investmentId = undefined;
}

/** 是否为iaa变更充值小程序 */
function iaaFlagChangeHandler() {
  formData.investmentId = undefined;
}

const virtualCurrencyBalanceCpt = computed(() => {
  const virtualCurrencyList = formData.dramaFirstTemplate.productList.filter((item) => item.productType === 1);
  for (const item of virtualCurrencyList) {
    if (item.productQuantity && formData.price) {
      if (Number(formData.price) > Number(item.productQuantity)) {
        item.numberOfEpisodes = 0;
        item.balance = item.productQuantity;
      } else {
        item.numberOfEpisodes = Math.floor(Number(item.productQuantity) / Number(formData.price)) + (Number(formData.rechargeEpisodeNum) || 0);
        item.balance = Number(item.productQuantity) % Number(formData.price);
      }
    } else {
      item.numberOfEpisodes = '';
      item.balance = '';
    }
  }
  return virtualCurrencyList;
});

/**
 * 选择模板
 */
function handleSelectTemplate(templateType: 1 | 2 | 4) {
  if (!disabled.value) {
    pageSelectTemplateRef.value?.show({
      templateType,
      selectCallBack(res: ReferralTemplate) {
        if (formData.productTemplateId !== res.productTemplateId) {

          console.log(res, "====res")

          formData.dramaFirstTemplate = res;
          formData.productTemplateId = res.productTemplateId!;
          formData.advertUnlock = res.advertUnlock;
          iapBackTemplate.value = undefined;
        }
      },
    });
  }
}

defineExpose({show, hide});
</script>

<style scoped lang="scss">
.content-vessel {
  display: grid;
  grid-template-columns: repeat(auto-fill, 259px);
  gap: 15px;
  width: 100%;

  .content-box {
    overflow: hidden;
    cursor: pointer;
    background: $c-bg-block;
    border-radius: 10px;
    box-shadow: var(--my-box-shadow-fill);

    .title-box {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      padding: 10px;
    }
  }
}
</style>
